<?php
namespace App\Controller\User;
use Think\Controller;
use Usap\Service\Account\user;
use Usap\Service\Message\Subscribe;
use Usap\Service\Service;
class SettingsController extends Controller{

	//服务定制
	public function customize(){
		$user_id = $this->context->userId;
		//$return_url = '/account/login?from='.rawurlencode('/settings/customize');


	/*初始化服务配置*/
		$serviceitems_conf = Service::instance()->loadConfig('system', 'customize','getServiceItems');
		
	/*初始化服务*/
		$customise_service = Service::instance()->find('system','customise');
		if(empty($user_id)){
                            $this->ajaxReturn(array('code'=>'-1001','code_str'=>"请先登录"));
                        }
		

			$item_name = I('param.item_name');//服务项名称
			$opt_type = I('param.opt_type');//操作项类型(on、off)
			$pwd_val = I('param.pwd_val');//校验密码
// 			$custom_cfg = I('param.custome_cfg',array());//个性化定制配置

			if($item_name=='noPwdPay' && $opt_type=='on'){//小额免密打开需要验证密码
				if(empty($pwd_val)){
					return $this->ajaxReturn(array('code'=>'-1001','code_str'=>'请输入登录密码'));
				}
				$user_service = Service::instance()->find('account','user');
				$check_info = $user_service->checkLoginPwd($user_id,$pwd_val);
				if($check_info['code']!='0000'){
                                        $data['code'] = $check_info['code'];
                                        $data['code_str'] = $check_info['msg'];
					return $this->ajaxReturn($data);
				}
			}
			

			if(!array_key_exists($item_name, $serviceitems_conf)){
				return $this->ajaxReturn(array('code'=>'-1002','code_str'=>'操作服务项不合法'));
			}

			if(!in_array($opt_type,array('on','off'))){
				return $this->ajaxReturn(array('code'=>'-1003','code_str'=>'操作类别不合法'));
			}
			
			$summary = $serviceitems_conf[$item_name]['summary'];
			$sub_summary = $serviceitems_conf[$item_name]['sub_summary'];
                       
			$relation_type = $serviceitems_conf[$item_name]['relation_type'];
                         //dprint($relation_type);die;
			if($relation_type=='follow'){

				if($opt_type=='on'){//关系定制

					$opt_result = $customise_service->subscribe('user',$user_id, $summary, $sub_summary, $relation_type);
                                       //dprint($opt_result);die;
				}else{//关系解除

					$opt_result = $customise_service->unsubscribe('user', $user_id, $summary, $sub_summary, $relation_type);
                                         
				}
			}else{
				if($opt_type=='off'){//关系定制

					$opt_result = $customise_service->subscribe('user',$user_id, $summary, $sub_summary, $relation_type);
				}else{//关系解除

					$opt_result = $customise_service->unsubscribe('user', $user_id, $summary, $sub_summary, $relation_type);
                                        
				}
			}
                        $data['code'] = $opt_result['code'];
                        $data['code_str'] = $opt_result['msg'];
			return $this->ajaxReturn($data);
                        
        }       
                        
                        
            public function getInfoStatus(){
                
             $user_id = $this->context->userId;

             /*初始化服务配置*/
	     $serviceitems_conf = Service::instance()->loadConfig('system', 'customize','getServiceItems');
             /*初始化服务*/
		$customise_service = Service::instance()->find('system','customise');
                
            if(empty($user_id)){
                            $this->ajaxReturn(array('code'=>'-1001','cod_str'=>"请先登录"));
                        }
                        
			
		/*获取我的服务状态*/
			$customise_list = array();
			foreach ($serviceitems_conf as $service_name=>$service_cfg){
				
				
				$status_info = $customise_service->getRelationStatus('user', $user_id, $service_cfg['summary'], $service_cfg['sub_summary'], $service_cfg['relation_type']);
				//dprint($status_info);die;

				$customise_list[$service_name]['code'] = '';
				if($status_info['code']=='0000' && $status_info['status']){

					$customise_list[$service_name]['status'] = $status_info['status'];
				}
			}
                        //dprint($customise_list);die;
			if(empty($customise_list)){
                            $this->ajaxReturn(array('code'=>'-1002','cod_str'=>"没有获取到当前状态",'info'=>''));
                        }else{
                            $this->ajaxReturn(array('code'=>'0000','cod_str'=>"获取到当前状态",'info'=>$customise_list));
                        }
		}


    /**
     * 订阅消息
     * @param string $category 类别
     * @param string $summary 子类别
     */
    public function subscribe($category = '', $summary = '') {
        $userId = $this->context->userId;

        if (empty($userId)) $this->ajaxReturn(array('code' => '-1001', 'cod_str' => "请先登录"));

        try {
            // $partId = getConfig("part_cloud_conf|{$_SERVER['SERVER_NAME']}|common|part_id");
            $partId = 0;
            $result = (new Subscribe($userId, $partId, $category, $summary))->sub('appmsg');
            if ($result) $this->ajaxReturn(array('code' => '0000', 'code_str' => '设置成功'));

            $this->ajaxReturn(array('code' => '-1002', 'code_str' => '设置失败'));
        } catch (\Exception $e) {
            $this->ajaxReturn(array('code' => '-1003', 'code_str' => $e->getMessage()));
        }
    }

    /**
     * 取消订阅消息
     * @param string $category 类别
     * @param string $summary 子类别
     */
    public function unSubscribe($category = '', $summary = '') {
        $userId = $this->context->userId;

        if (empty($userId)) $this->ajaxReturn(array('code' => '-1001', 'cod_str' => "请先登录"));

        try {
            //$partId = getConfig("part_cloud_conf|{$_SERVER['SERVER_NAME']}|common|part_id");
            $partId = 0;
            $result = (new Subscribe($userId, $partId, $category, $summary))->unSub('appmsg');
            if ($result) $this->ajaxReturn(array('code' => '0000', 'code_str' => '设置成功'));

            $this->ajaxReturn(array('code' => '-1002', 'code_str' => '设置失败'));
        } catch (\Exception $e) {
            $this->ajaxReturn(array('code' => '-1003', 'code_str' => $e->getMessage()));
        }
    }

    /**
     * 订阅消息信息
     * @param string $category 类别
     * @param string $summary 子类别
     */
    public function subscribeStatus($category = '', $summary = '') {
        $userId = $this->context->userId;

        if (empty($userId)) $this->ajaxReturn(array('code' => '-1001', 'cod_str' => "请先登录"));

        try {
            // $partId = getConfig("part_cloud_conf|{$_SERVER['SERVER_NAME']}|common|part_id");
            $partId = 0;
            $result = (new Subscribe($userId, $partId))->subStatus();
            $this->ajaxReturn(array('code' => '0000', 'code_str' => '获取成功', 'info' => $result));
        } catch (\Exception $e) {
            $this->ajaxReturn(array('code' => '-1003', 'code_str' => $e->getMessage()));
        }
    }

    /**
     * 获取设置状态
     */
    public function getSettingStatus() {
        $userId = $this->context->userId;

        /* 获取我的服务状态 */
        if (!empty($userId)) {
            $subscribeService = new Subscribe($userId, 0);
            $subStatus = $subscribeService->subStatus();
            $return = [
                'code' => '0000',
                'info' => [
                    'openPrizeStatus' => $subStatus['openPrize']['status'],
                    'noPwdPayStatus'  => $subStatus['cashier']['summary']['nopwdpay']['status']
                ]
            ];
        } else {
            $return = [
                'code' => '0000',
                'info' => [
                    'openPrizeStatus' => 'off',
                    'noPwdPayStatus'  => 'off'
                ]
            ];
        }

        $this->ajaxReturn($return);
    }

    /**
     * 设置开奖通知
     *
     * @param string $opt
     */
    public function setOpenPrize($opt = 'on') {
        $userId = $this->context->userId;
        try {
            $subscribe = new Subscribe($userId, 0, 'openPrize');

            if ($opt == 'on') $result = $subscribe->subCategory();
            else $result = $subscribe->unSub();

            if ($result) $this->ajaxReturn(array('code' => '0000', 'code_str' => '设置成功'));
            $this->ajaxReturn(array('code' => '-1002', 'code_str' => '设置失败'));
        } catch (\Exception $e) {
            $this->ajaxReturn(array('code' => '-1003', 'code_str' => $e->getMessage()));
        }
    }

    /**
     * 设置小额免密
     *
     * @param string $opt 操作，on/off
     * @param string $pwd 密码
     */
    function setNoPwdPay($opt, $pwd = '') {
        $userId = $this->context->userId;
        try {
            if ($opt == 'on') {
                if (empty($pwd)) $this->ajaxReturn(['code' => '-1000', 'msg' => '请输入登录密码']);
                $checkInfo = (new user())->checkLoginPwd($userId, $pwd);
                if ($checkInfo['code'] != '0000') $this->ajaxReturn($checkInfo);
                $result = (new Subscribe($userId, 0, 'cashier', 'nopwdpay'))->sub('sms');
            } else {
                $result = (new Subscribe($userId, 0, 'cashier', 'nopwdpay'))->unSub('sms');
            }

            if ($result) $this->ajaxReturn(array('code' => '0000', 'code_str' => '设置成功'));
            $this->ajaxReturn(array('code' => '-1002', 'code_str' => '设置失败'));
        } catch (\Exception $e) {
            $this->ajaxReturn(array('code' => '-1003', 'code_str' => $e->getMessage()));
        }
    }
}